import bmesh
import bpy
from bpy.types import Operator
from mathutils import Vector

class Import_Obj_Op(Operator):
    bl_idname = "object.import_obj"
    bl_label = "import obj"
    bl_description = "import a obj"

    def execute(self,context):
        # bpy.ops.import_scene.obj(filepath=r"C:\Users\tomye\Documents\untitled.obj")
        obj = bpy.data.objects[0]
        print(obj.name)

        x1=-0.108585
        y1=7.27485
        x2=-0.108585
        y2=7.27485
        
        dst = Vector((x1, y1, 0))
        src = Vector((x2, y2, 10))
        
        mw = obj.matrix_world
        mwi = mw.inverted()

        # 把src和dst两个世界坐标系下的向量转为物体坐标系
        origin = mwi @ src
        dest = mwi @ dst
        direction = (dest - origin).normalized()

        hit, loc, norm, face = obj.ray_cast(origin, direction)
        
        loc = mw.to_3x3().inverted().transposed() @ loc # loc是物体坐标系，需要转为世界坐标系
        
        verts = [(loc[0],loc[1],loc[2]),(loc[0],loc[1],0),(loc[0],loc[1],10),(x1,y1,0),(x2,y2,10)]
        line = []

        if hit:
            print(loc)
            lines = [(2,0)]
        else:
            print('没有相交')
            lines = [(3,4)]

        # Create Mesh Datablock
        mesh = bpy.data.meshes.new('ray')
        mesh.from_pydata(verts, lines, [])

        obj = bpy.data.objects.new('ray', mesh)
        bpy.context.scene.collection.objects.link(obj)
        return {'FINISHED'}